package com.ycb.utils;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.cookie.Cookie;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.message.BasicHeader;

import java.io.IOException;
import java.util.function.Consumer;

/**
 * @author 黄泽群
 * @since 2024-01-16
 */
public class HttpClientUtil {

    private static final JdCookieStore cookieStore = new JdCookieStore("D:\\2jd.cookie");


    public static String getCookieValue(String cookieName){
        Cookie cookie = getCookie(cookieName);
        return cookie == null ? null : cookie.getValue();
    }

    public static Cookie getCookie(String cookieName){
        return cookieStore.getCookie(cookieName);
    }

    public static void httpGet(String url, Consumer<HttpEntity> counter, BasicHeader... headers) throws IOException {
        httpGet(url,counter,true,headers);
    }

    public static void httpGet(String url, Consumer<HttpEntity> counter,boolean saveCookie, BasicHeader... headers) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader(cookieStore.getCookieHeader());
        for (BasicHeader header : headers) {
            httpGet.setHeader(header);
        }
        try (CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore.getCookieStore())
                .setUserAgent(Constant.HEADER_AGENT_ARG)
                .build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                counter.accept(response.getEntity());
            }
            if (saveCookie) {
                cookieStore.saveCookie();
            }
        } catch (Exception e) {
            throw e;
        }
    }




}
